package com.xiaoyang.friend.service.exam.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaoyang.common.core.constants.Constants;
import com.xiaoyang.common.core.domain.TableDataInfo;
import com.xiaoyang.common.core.utils.ThreadLocalUtil;
import com.xiaoyang.friend.domain.exam.dto.ExamQueryDTO;
import com.xiaoyang.friend.domain.exam.dto.ExamRankDTO;
import com.xiaoyang.friend.domain.exam.vo.ExamRankVO;
import com.xiaoyang.friend.domain.exam.vo.ExamVO;
import com.xiaoyang.friend.domain.user.vo.UserVO;
import com.xiaoyang.friend.manager.ExamCacheManager;
import com.xiaoyang.friend.manager.UserCacheManager;
import com.xiaoyang.friend.mapper.exam.ExamMapper;
import com.xiaoyang.friend.mapper.user.UserExamMapper;
import com.xiaoyang.friend.service.exam.IExamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private ExamCacheManager examCacheManager;

    @Autowired
    private UserCacheManager userCacheManager;

    /**
     * 竞赛列表
     * @param examQueryDTO
     * @return
     */
    @Override
    public List<ExamVO> list(ExamQueryDTO examQueryDTO) {
        log.info("查询竞赛列表");
        // 分页查询
        PageHelper.startPage(examQueryDTO.getPageNum(), examQueryDTO.getPageSize());
        return examMapper.selectExamList(examQueryDTO);
    }

    /**
     * 竞赛列表redis版
     * @param examQueryDTO
     */
    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        log.info("redis--查询竞赛列表");
        //从redis当中获取  竞赛列表的数据
        Long total = examCacheManager.getListSize(examQueryDTO.getType(), null);
        List<ExamVO> examVOList;
        if (total == null || total <= 0) {
            examVOList = list(examQueryDTO);
            examCacheManager.refreshCache(examQueryDTO.getType(), null);
            total = new PageInfo<>(examVOList).getTotal();
        } else {
            examVOList = examCacheManager.getExamVOList(examQueryDTO, null);
            total = examCacheManager.getListSize(examQueryDTO.getType(), null);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamVOList(examVOList);
        return TableDataInfo.success(examVOList, total);
    }

    /**
     * 竞赛排行榜
     * @param examRankDTO
     * @return
     */
    @Override
    public TableDataInfo rankList(ExamRankDTO examRankDTO) {
        log.info("查询竞赛排行榜");

        //从redis当中获取  竞赛列表的数据
        Long total = examCacheManager.getRankListSize(examRankDTO.getExamId());
        List<ExamRankVO> examRankVOList;
        if (total == null || total <= 0) {
            PageHelper.startPage(examRankDTO.getPageNum(), examRankDTO.getPageSize());
            examRankVOList = userExamMapper.selectExamRankList(examRankDTO.getExamId());
            examCacheManager.refreshExamRankCache(examRankDTO.getExamId());
            total = new PageInfo<>(examRankVOList).getTotal();
        } else {
            examRankVOList = examCacheManager.getExamRankVOList(examRankDTO);
        }
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamRankVOList(examRankVOList);
        return TableDataInfo.success(examRankVOList, total);
    }

    /**
     * 获取竞赛的第一道题
     * @param examId
     * @return
     */
    @Override
    public String getFirstQuestion(Long examId) {
        log.info("获取{}的第一道题", examId);
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if (listSize == null || listSize <= 0) {
            // 缓存中没有数据，则从数据库中获取
            examCacheManager.refreshExamQuestionCache(examId);
        }

        // 从缓存中获取第一道题id
        return examCacheManager.getFirstQuestion(examId).toString();
    }

    /**
     * 获取竞赛的上一道题
     * @param examId
     * @param questionId
     * @return
     */
    @Override
    public String preQuestion(Long examId, Long questionId) {
        log.info("获取{}的{}的上一道题", examId, questionId);

        // 从redis中查询题目是否存在
        checkAndRefresh(examId);

        return examCacheManager.preQuestion(examId, questionId).toString();
    }

    /**
     * 获取竞赛的下一道题
     * @param examId
     * @param questionId
     * @return
     */
    @Override
    public String nextQuestion(Long examId, Long questionId) {
        log.info("获取{}的{}的下一道题", examId, questionId);

        // 从redis中查询题目是否存在
        checkAndRefresh(examId);
        return examCacheManager.nextQuestion(examId, questionId).toString();
    }

    /**
     * 检查redis中是否有数据，没有则刷新
     * @param examId
     */
    private void checkAndRefresh(Long examId) {
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if (listSize == null || listSize <= 0) {
            // redis中没有数据，则刷新redis
            examCacheManager.refreshExamQuestionCache(examId);
        }
    }

    /**
     * 组装竞赛排行榜数据
     * @param examRankVOList
     */
    private void assembleExamRankVOList(List<ExamRankVO> examRankVOList) {
        log.info("组装竞赛排行榜数据");

        if (CollectionUtil.isEmpty(examRankVOList)) {
            return;
        }
        for (ExamRankVO examRankVO : examRankVOList) {
            Long userId = examRankVO.getUserId();
            UserVO user = userCacheManager.getUserById(userId);
            examRankVO.setNickName(user.getNickName());
        }
    }

    /**
     * 组装竞赛列表数据
     * @param examVOList
     */
    private void assembleExamVOList(List<ExamVO> examVOList) {
        log.info("组装竞赛列表数据");
        Long userId = ThreadLocalUtil.get(Constants.USER_ID, Long.class);

        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);

        if (CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }

        for (ExamVO examVO : examVOList) {
            if (userExamIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }
}
